<!-- 图片选择 -->
<template>
  <el-dialog
    v-model="display"
    title="选择图片"
    width="1106px"
    :append-to-body="true"
    class="an-dialog"
  >
    <!-- tabs栏 -->
    <div class="c1">
      <div class="c2 flex">
        <div
          class="c3"
          :style="{
            borderColor:
              pageData.selectIndex == i ? 'var(--el-color-primary)' : '#eee',
          }"
          v-for="(v, i) in pageData.list"
          :key="i"
          @click="selectImg(v, i)"
        >
          <el-image
            style="width: 70px; height: 70px"
            :src="config.serverImg + v.key + '?imageView2/0/format/webp/q/75'"
            fit="contain"
          ></el-image>
        </div>
      </div>
    </div>

    <div class="flex c5">
      <!-- 分页 -->
      <el-pagination
        background
        @size-change="switchSizeChange"
        @current-change="switchCurrentChange"
        v-model:currentPage="pageData.page"
        :default-page-size="pageData.limit"
        layout="total,prev, pager, next"
        :page-sizes="[60, 100]"
        :total="pageData.total"
      >
      </el-pagination>

      <!-- 底部按钮 -->
      <div class="flex c4">
        <el-button type="primary" class="c6">
          <input
            type="file"
            ref="uploadInput"
            accept="image/jpg, image/jpeg, image/png"
            @change="cuttingFile"
          />
          上传图片
        </el-button>
        <el-button type="primary" @click="successImg('success')"
          >确定选择</el-button
        >
        <el-button @click="display = false">取消</el-button>
      </div>
    </div>
  </el-dialog>

  <!-- 图片裁剪组件 -->
  <cropper-img
    v-model:show="cutting.show"
    :name="tabsName"
    :pic="cutting.pic"
    @img="cuttingSuccess"
  >
  </cropper-img>
</template>

<script setup>
import cropperImg from "@/components/cropper-img.vue";
import upImg from "@/hook/upimg.js";
import config from "@/common/config.js";
const api = inject("api");
const { upQiniu, imgFun, getQnToken, delQnImg } = upImg(); //获取上传配置
const emit = defineEmits(["img", "update:show"]);
const props = defineProps({
  show: {
    type: Boolean,
    default: false,
  },
  name: {
    type: String,
    default: "",
  },
  //空间名称
  spaceValue: {
    type: String,
    default: "local",
  },
});

const tabsName = ref("other"); //默认tabs栏
localStorage.setItem("prefix", tabsName.value);

const display = ref(true);

//裁剪组件配置
const uploadInput = ref(null); //获取上传裁剪图片按钮
const cutting = reactive({
  show: false,
  pic: "",
});

//选择图片裁剪
const cuttingFile = (e) => {
  console.log(666);
  cutting.pic = "";
  // 获取选取的文件
  const target = e.target;
  const { files } = target;
  if (!files) return;
  const file = files[0];
  // 转换为base64传给裁切组件
  const reader = new FileReader();
  reader.readAsDataURL(file);
  reader.onload = () => {
    emit("update:show", false);

    // 更新裁切弹窗的图片源
    cutting.pic = String(reader.result);
    cutting.show = true;

    // 清空已选择的文件
    if (!uploadInput.value) return;
    uploadInput.value.value = "";
  };
};

//裁剪成功
const cuttingSuccess = (res) => {
  console.log(res);
  emit("img", { value: res.value, name: "" });
  pageData.page = 1;
  getList();
};

watch(
  props,
  (newVal, oldVal) => {
    display.value = newVal.show;
    if (display.value && !pageData.list.length) {
      getList();
    }
    if (newVal.spaceValue) {
      tabsName.value = newVal.spaceValue;
      localStorage.setItem("prefix", tabsName.value);
    }
  },
  { immediate: true }
);

watch(
  display,
  (newVal, oldVal) => {
    emit("update:show", newVal);
  },
  { immediate: true }
);

// 页面数据
const pageData = reactive({
  list: [], //列表
  spaceList: config.spaceList,
  total: 0,
  page: 1,
  limit: 65,
  selectIndex: -1,
  selectValue: null,
});

//上传成功
const imgSuccess = (res) => {
  api
    .post("api/Img/up_data", {
      prefix: tabsName.value,
      key: res.key,
    })
    .then((r) => {
      emit("img", { value: res.key, name: "" });
      pageData.page = 1;
      getList();
    });
};

//切换列表
const handleClick = (tab, event) => {
  localStorage.setItem("prefix", tabsName.value);
  setTimeout(() => {
    pageData.page = 1;
    getList();
  }, 0);
};

//获取列表
const getList = () => {
  api
    .post("api/Img/get_list", {
      prefix: tabsName.value,
      limit: pageData.limit,
      page: pageData.page,
    })
    .then((res) => {
      pageData.total = res.total;
      pageData.list = res.data.list.map((r) => {
        return {
          id: r.id,
          key: r.key,
        };
      });
    });
};

// 切换每页条数
const switchSizeChange = (val) => {
  console.log(`每页 ${val} 条`);
  pageData.limit = val;
  getList();
};

// 点击分页
const switchCurrentChange = (val) => {
  console.log(`当前页: ${val}`);
  // document.getElementById("right").scrollTop = 0;//滚动条置顶
  getList();
};

//选择图片
const selectImg = (v, index) => {
  pageData.selectIndex = index;
  pageData.selectValue = v.key;
};

//确定图片
const successImg = (type) => {
  if (type == "success") {
    //返回 value文件名称 url空间域名 name标识需要上传图片的dom
    emit("img", { value: pageData.selectValue, name: props.name });
  } else {
    emit("img", null);
  }
};
</script>
<style>
.el-dialog .el-dialog__body {
  padding: 10px;
}
</style>
<style scoped lang="scss">
.c1 {
  .c2 {
    flex-wrap: wrap;
  }
  .c3 {
    width: 72px;
    height: 72px;
    border: 1px solid #ddd;
    background: #fff;
    margin: 5px;
  }
  .c3:hover {
    border-color: var(--el-color-primary);
    cursor: pointer;
  }
}
.c4 {
  justify-content: flex-end;
  margin-top: 10px;
}
.c4 .a-but {
  margin-left: 20px;
}
.c5 {
  margin-top: 10px;
  justify-content: space-between;
  align-items: flex-end;
}
.c6 {
  position: relative;
  overflow: hidden;
}
.c6 input {
  position: absolute;
  font-size: 100px;
  right: 0;
  top: 0;
  opacity: 0;
  filter: alpha(opacity=0);
  cursor: pointer;
}
</style>
